<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="文章源地址：Optimizing A Vue App 在构建我们的 Web 应用程序时优先考虑性能可以改善用户体验，有助于确保尽可能多的人可以使用它们。在本文中，Michelle Barker 将向您介绍一些前端优化技巧，以保持我们的 Vue 应用程序尽可能高效。">
<meta property="og:type" content="article">
<meta property="og:title" content="优化你的Vue应用">
<meta property="og:url" content="https://wyatex.online/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="文章源地址：Optimizing A Vue App 在构建我们的 Web 应用程序时优先考虑性能可以改善用户体验，有助于确保尽可能多的人可以使用它们。在本文中，Michelle Barker 将向您介绍一些前端优化技巧，以保持我们的 Vue 应用程序尽可能高效。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wyatex.online/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/1.png">
<meta property="article:published_time" content="2022-11-30T13:00:59.000Z">
<meta property="article:modified_time" content="2023-05-05T01:25:47.394Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="+ JavaScript + 前端 + 翻译 + Vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wyatex.online/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/1.png">


<link rel="canonical" href="https://wyatex.online/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/","path":"Vue/优化你的Vue应用/","title":"优化你的Vue应用"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>优化你的Vue应用 | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<script src="/assets/js/DPlayer.min.js"></script></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%80%89%E6%8B%A9%E6%A1%86%E6%9E%B6"><span class="nav-number">1.</span> <span class="nav-text">选择框架</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E6%9E%84%E5%BB%BA%E5%B7%A5%E5%85%B7%E6%91%87%E6%A0%91%E3%80%81%E5%8E%8B%E7%BC%A9%E5%92%8C%E6%9C%80%E5%B0%8F%E5%8C%96"><span class="nav-number">2.</span> <span class="nav-text">使用构建工具摇树、压缩和最小化</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vue-%E7%BB%84%E5%90%88-API"><span class="nav-number">3.</span> <span class="nav-text">Vue 组合 API</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AF%BC%E5%85%A5%E4%BE%9D%E8%B5%96%E9%A1%B9"><span class="nav-number">4.</span> <span class="nav-text">导入依赖项</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E5%8A%A8%E6%80%81%E5%AF%BC%E5%85%A5%E8%BF%9B%E8%A1%8C%E4%BB%A3%E7%A0%81%E6%8B%86%E5%88%86"><span class="nav-number">5.</span> <span class="nav-text">使用动态导入进行代码拆分</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-Vue-%E8%B7%AF%E7%94%B1%E5%99%A8%E7%9A%84%E5%BB%B6%E8%BF%9F%E5%8A%A0%E8%BD%BD%E8%B7%AF%E7%94%B1"><span class="nav-number">6.</span> <span class="nav-text">使用 Vue 路由器的延迟加载路由</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%82%E6%AD%A5%E7%BB%84%E4%BB%B6"><span class="nav-number">7.</span> <span class="nav-text">异步组件</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%8B%86%E5%88%86-API-%E8%AF%B7%E6%B1%82"><span class="nav-number">8.</span> <span class="nav-text">拆分 API 请求</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%9C%89%E6%9D%A1%E4%BB%B6%E5%9C%B0%E5%8A%A0%E8%BD%BD%E7%BB%84%E4%BB%B6"><span class="nav-number">9.</span> <span class="nav-text">有条件地加载组件</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#CSS"><span class="nav-number">10.</span> <span class="nav-text">CSS</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BC%98%E5%8C%96%E5%8A%A0%E8%BD%BD%E7%8A%B6%E6%80%81"><span class="nav-number">11.</span> <span class="nav-text">优化加载状态</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%AD%E6%AD%A2-API-%E8%AF%B7%E6%B1%82"><span class="nav-number">12.</span> <span class="nav-text">中止 API 请求</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-stale-while-revalidate-%E4%BF%9D%E6%8C%81%E6%96%B0%E9%B2%9C%E5%BA%A6"><span class="nav-number">13.</span> <span class="nav-text">使用 stale-while-revalidate 保持新鲜度</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%9B%B4%E6%96%B0%E6%8C%87%E7%A4%BA%E5%99%A8"><span class="nav-number">14.</span> <span class="nav-text">更新指示器</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BB%93%E8%AE%BA"><span class="nav-number">15.</span> <span class="nav-text">结论</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="优化你的Vue应用 | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          优化你的Vue应用
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-11-30 21:00:59" itemprop="dateCreated datePublished" datetime="2022-11-30T21:00:59+08:00">2022-11-30</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-05-05 09:25:47" itemprop="dateModified" datetime="2023-05-05T09:25:47+08:00">2023-05-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>文章源地址：<a target="_blank" rel="noopener" href="https://www.smashingmagazine.com/2022/11/optimizing-vue-app/">Optimizing A Vue App</a></p>
<p>在构建我们的 Web 应用程序时优先考虑性能可以改善用户体验，有助于确保尽可能多的人可以使用它们。在本文中，Michelle Barker 将向您介绍一些前端优化技巧，以保持我们的 Vue 应用程序尽可能高效。</p>
<span id="more"></span>

<p>单页应用程序 （SPA） 可以在处理实时动态数据时提供丰富的交互式用户体验。但它们也可能很重、臃肿而且表现不佳（或者说速度很慢?）。在本文中，我们将介绍一些前端优化技巧，以保持我们的 Vue 应用程序相对精简，并且按需打包我们需要的 JS。</p>
<blockquote>
<p>注意: 虽然假设你对Vue和 Composition API 有一定的了解，但是希望这篇文章对你来说你选择什么框架都能有所收获</p>
</blockquote>
<p>作为Ada Mode的前端开发人员，我的工作涉及维护Windscope，这是一个供风电场运营商管理和维护其涡轮机组的网络应用程序。由于需要实时接收数据以及所需的高度交互性，因此为该项目选择了SPA架构。我们的 Web 应用程序依赖于一些庞大的 JS 库，但我们希望通过尽可能快速高效地获取数据和渲染来为最终用户提供最佳体验。</p>
<h1 id="选择框架"><a href="#选择框架" class="headerlink" title="选择框架"></a>选择框架</h1><p>我们选择的JS框架是Vue，部分原因是它是我最熟悉的框架。以前，与 React 相比，Vue 的整体捆绑包大小更小。然而，自从最近的 React 更新以来，React在这方面似乎做得更好。这不一定重要，因为在本文中，我们将介绍如何仅导入所需的内容。这两个框架都有优秀的文档和庞大的开发人员生态系统（社区环境），这是另一个考虑因素。Svelte是另一种可能的选择，但由于不熟悉，它需要更陡峭的学习曲线，而且由于较新，它的生态系统不太发达。<br>作为演示各种优化的示例，我构建了一个简单的 Vue 应用程序，该应用程序从 API 获取数据并使用D3.js 渲染一些图表。</p>
<img data-src="/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/1.png" class="">

<blockquote>
<p>注意：完整代码请参考示例 <a target="_blank" rel="noopener" href="https://github.com/mbarker84/vue-app-example">GitHub</a> 仓库。</p>
</blockquote>
<p>我们正在使用Parcel（一种最小配置构建工具）来打包我们的应用，但我们在此处介绍的所有优化都适用于您选择的任何打包工具。</p>
<h1 id="使用构建工具摇树、压缩和最小化"><a href="#使用构建工具摇树、压缩和最小化" class="headerlink" title="使用构建工具摇树、压缩和最小化"></a>使用构建工具摇树、压缩和最小化</h1><p>最好只打包您需要的代码，并且开箱即用，Parcel 会在构建过程中删除未使用的 Javascript 代码（摇树）。它还可以最小化代码，并且可以配置使用 Gzip 或 Brotli 进行压缩输出。</p>
<p>除了缩小，Parcel 还采用范围提升作为其生产过程的一部分，这有助于提高缩小效率。范围提升的深入指南不在本文的范围之内（看看我在那里做了什么？尽管如此，如果在我们的示例应用程序上带 <code>--no-optimize --no-scope-hoist</code> 运行 Parcel 的构建过程，我们可以看到生成的捆绑包为 510kB - 大约是优化和缩小版本的5 倍。因此，无论您使用哪种打包工具，都可以公平地说，您可能希望确保它执行尽可能多的优化。</p>
<p>但工作并没有就此结束。即使我们总体上发布了一个较小的捆绑包，浏览器仍然需要时间来解析和编译我们的 JS，这可能会导致用户体验变慢。这篇关于 Calibre 的<a target="_blank" rel="noopener" href="https://calibreapp.com/blog/bundle-size-optimization">打包大小优化</a>的文章解释了大型 JS 包如何影响性能指标。</p>
<p>让我们看看我们还能做些什么来减少浏览器必须做的工作量。</p>
<blockquote>
<p>这里我还是更推荐使用vite去作为打包工具，能大幅提高打包效率和拥护更大的插件生态</p>
</blockquote>
<h1 id="Vue-组合-API"><a href="#Vue-组合-API" class="headerlink" title="Vue 组合 API"></a>Vue 组合 API</h1><p>Vue 3 引入了 Composition API作为选项API 的替代方案，这是一组新的 API用于编写组件。通过专门使用 Composition API，我们可以只导入我们需要的 Vue 函数，而不是整个包。它还使我们能够使用可组合代码编写更多可复用代码。使用 Composition API 编写的代码小，并且整个应用程序更容易进行摇树优化。</p>
<p>注意：如果你使用的是旧版本的 Vue，你仍然可以使用 Composition API：它被向后移植到 Vue 2.7，并且有一个<a target="_blank" rel="noopener" href="https://github.com/vuejs/composition-api">旧版本的官方插件</a>。</p>
<h1 id="导入依赖项"><a href="#导入依赖项" class="headerlink" title="导入依赖项"></a>导入依赖项</h1><p>一个关键目标是减少客户端下载的初始 JS 包的大小。Windscope广泛使用D3进行数据可视化，这是一个大型库，范围广泛。但是，Windscope只需要其中的一部分（D3库中有我们根本不需要的整个模块）。如果我们在 <a target="_blank" rel="noopener" href="https://bundlephobia.com/">Bundlephobia</a> 上检查整个 D3 包，我们可以看到我们的应用程序使用的可用模块不到一半，甚至可能不是这些模块中的所有功能(方法&#x2F;函数)。</p>
<p>保持我们的捆绑包大小尽可能小的最简单方法之一是仅导入我们需要的模块。</p>
<p>让我们以 D3 的函数为例。我们可以使用模块导入所需的函数，而不是使用默认导入</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Previous:</span></span><br><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> d3 <span class="keyword">from</span> <span class="string">&#x27;d3&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Instead:</span></span><br><span class="line"><span class="keyword">import</span> &#123;</span><br><span class="line">    selectAll</span><br><span class="line">&#125; <span class="keyword">from</span> <span class="string">&#x27;d3-selection&#x27;</span></span><br></pre></td></tr></table></figure>

<h1 id="使用动态导入进行代码拆分"><a href="#使用动态导入进行代码拆分" class="headerlink" title="使用动态导入进行代码拆分"></a>使用动态导入进行代码拆分</h1><p>在整个Windscope的很多地方都使用了某些软件包，例如AWS Amplify身份验证库，特别是 <code>Auth</code> (身份校验)方法。这是一个很大的依赖关系，对我们的 JS 包大小影响非常大。动态导入不是在文件顶部静态导入模块，而是在代码中需要它的时候允许我们精准的导入模块。</p>
<p>而不是：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;</span><br><span class="line">    <span class="title class_">Auth</span></span><br><span class="line">&#125; <span class="keyword">from</span> <span class="string">&#x27;@aws-amplify/auth&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> user = <span class="title class_">Auth</span>.<span class="title function_">currentAuthenticatedUser</span>()</span><br></pre></td></tr></table></figure>

<p>当我们想要使用它时，我们可以导入它：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(<span class="string">&#x27;@aws-amplify/auth&#x27;</span>).<span class="title function_">then</span>(<span class="function">(<span class="params">&#123;</span></span></span><br><span class="line"><span class="params"><span class="function">    Auth</span></span></span><br><span class="line"><span class="params"><span class="function">&#125;</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> user = <span class="title class_">Auth</span>.<span class="title function_">currentAuthenticatedUser</span>()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>这意味着该模块将被拆分为一个单独的JS包（或“块”），浏览器将在需要时下载该包。此外，浏览器可以缓存这些依赖项，这些依赖项的更改频率可能低于我们应用程序其余部分的代码。</p>
<h1 id="使用-Vue-路由器的延迟加载路由"><a href="#使用-Vue-路由器的延迟加载路由" class="headerlink" title="使用 Vue 路由器的延迟加载路由"></a>使用 Vue 路由器的延迟加载路由</h1><p>我们的应用程序使用 <code>vue-router</code> 进行导航。与动态导入类似，我们可以延迟加载路由组件，因此只有在用户导航到该路由时才会导入它们（以及它们关联的依赖项）。</p>
<p>在我们 <code>index/router.js</code> 的代码中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 先前:</span></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Home</span> <span class="keyword">from</span> <span class="string">&quot;../routes/Home.vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">About</span> <span class="keyword">from</span> <span class="string">&quot;../routes/About.vue&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用懒加载代替:</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">Home</span> = (<span class="params"></span>) =&gt; <span class="keyword">import</span>(<span class="string">&quot;../routes/Home.vue&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title function_">About</span> = (<span class="params"></span>) =&gt; <span class="keyword">import</span>(<span class="string">&quot;../routes/About.vue&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> routes = [&#123;</span><br><span class="line">        <span class="attr">name</span>: <span class="string">&quot;home&quot;</span>,</span><br><span class="line">        <span class="attr">path</span>: <span class="string">&quot;/&quot;</span>,</span><br><span class="line">        <span class="attr">component</span>: <span class="title class_">Home</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="attr">name</span>: <span class="string">&quot;about&quot;</span>,</span><br><span class="line">        <span class="attr">path</span>: <span class="string">&quot;/about&quot;</span>,</span><br><span class="line">        <span class="attr">component</span>: <span class="title class_">About</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">];</span><br></pre></td></tr></table></figure>

<p>仅当用户单击“关于”链接并导航到该页面时，才会加载“关于”页面的代码。</p>
<h1 id="异步组件"><a href="#异步组件" class="headerlink" title="异步组件"></a>异步组件</h1><p>了延迟加载每条路由之外，我们还可以使用 Vue 的 <code>defineAsyncComponent</code> 方法延迟加载单个组件。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">KPIComponent</span> = <span class="title function_">defineAsyncComponent</span>(<span class="function">() =&gt;</span> <span class="keyword">import</span>(<span class="string">&#x27;../components/KPI.vue))</span></span><br></pre></td></tr></table></figure>

<p>这意味着 KPI 组件的代码将被动态导入，正如我们在路由器示例中所看到的那样。我们还可以提供一些组件，以便在它处于加载或错误状态时显示（如果我们加载一个特别大的文件，这很有用）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">KPIComponent</span> = <span class="title function_">defineAsyncComponent</span>(&#123;</span><br><span class="line">    <span class="attr">loader</span>: <span class="function">() =&gt;</span> <span class="keyword">import</span>(<span class="string">&#x27;../components/KPI.vue&#x27;</span>),</span><br><span class="line">    <span class="attr">loadingComponent</span>: <span class="title class_">Loader</span>,</span><br><span class="line">    <span class="attr">errorComponent</span>: <span class="title class_">Error</span>,</span><br><span class="line">    <span class="attr">delay</span>: <span class="number">200</span>,</span><br><span class="line">    <span class="attr">timeout</span>: <span class="number">5000</span>,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h1 id="拆分-API-请求"><a href="#拆分-API-请求" class="headerlink" title="拆分 API 请求"></a>拆分 API 请求</h1><p>我们的应用程序主要关注数据可视化，严重依赖从服务器获取大量数据。其中一些请求可能非常慢，因为服务器必须对数据执行大量计算。在我们的初始原型中，我们向每个路由的 REST API 发出了一个请求。不幸的是，我们发现这导致用户不得不等待很长时间 - 有时长达 10 秒，在应用程序成功接收数据并开始渲染可视化之前观看加载微调器。</p>
<p>我们决定将 API 拆分为多个端点，并为每个小部件发出请求。虽然这可能会增加整体响应时间，但这意味着应用程序应该更快地可用，因为用户将在等待其他页面时看到页面的一部分呈现。此外，可能发生的任何错误都将本地化，而页面的其余部分仍然可用。</p>
<p>您可以看到此处说明的差异：</p>
<div id="dplayer0" class="dplayer hexo-tag-dplayer-mark" style="margin-bottom: 20px;"></div><script>(function(){var player = new DPlayer({"container":document.getElementById("dplayer0"),"theme":"#FADFA3","loop":true,"video":{"url":"https://gitee.com/wyatex/wyatex/raw/master/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/2.mp4"}});window.dplayers||(window.dplayers=[]);window.dplayers.push(player);})()</script>

<blockquote>
<p>在右侧的示例中，用户可以与某些组件进行交互，而其他组件仍在请求数据。左侧的页面必须等待大型数据响应，然后才能呈现并具有交互性。</p>
</blockquote>
<h1 id="有条件地加载组件"><a href="#有条件地加载组件" class="headerlink" title="有条件地加载组件"></a>有条件地加载组件</h1><p>现在我们可以将其与异步组件结合使用，以便仅在收到来自服务器的成功响应时加载组件。在这里，我们获取数据，然后在 <code>fetch</code> 函数成功返回时导入组件：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">component</span> <span class="attr">:is</span>=<span class="string">&quot;KPIComponent&quot;</span> <span class="attr">:data</span>=<span class="string">&quot;data&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">component</span>&gt;</span> </span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&lt;/template&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">import</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    defineComponent,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    ref,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    defineAsyncComponent</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">&#125; <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">import</span> <span class="title class_">Loader</span> <span class="keyword">from</span> <span class="string">&quot;./Loader&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">import</span> <span class="title class_">Error</span> <span class="keyword">from</span> <span class="string">&quot;./Error&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">defineComponent</span>(&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="attr">components</span>: &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title class_">Loader</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title class_">Error</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">setup</span>(<span class="params"></span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="keyword">const</span> data = <span class="title function_">ref</span>(<span class="literal">null</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="keyword">const</span> <span class="title function_">loadComponent</span> = (<span class="params"></span>) =&gt; &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                    <span class="keyword">return</span> <span class="title function_">fetch</span>(<span class="string">&#x27;https://api.npoint.io/ec46e59905dc0011b7f4&#x27;</span>)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> response.<span class="title function_">json</span>())</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> (data.<span class="property">value</span> = response))</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        .<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="keyword">import</span>(<span class="string">&quot;../components/KPI.vue&quot;</span>) <span class="comment">// Import the component</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                            .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">error</span>(e));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                    <span class="keyword">const</span> <span class="title class_">KPIComponent</span> = <span class="title function_">defineAsyncComponent</span>(&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="attr">loader</span>: loadComponent,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="attr">loadingComponent</span>: <span class="title class_">Loader</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="attr">errorComponent</span>: <span class="title class_">Error</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="attr">delay</span>: <span class="number">200</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="attr">timeout</span>: <span class="number">5000</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                    &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                    <span class="keyword">return</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        data,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="title class_">KPIComponent</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                    &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        )</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

<p>为了处理每个组件的此过程，我们创建了一个称为 <code>WidgetLoader</code> 的高阶组件，您可以在仓库中看到该组件。</p>
<p>此模式可以扩展到应用中在用户交互时呈现组件的任何位置。例如，在Windscope中，我们仅在用户单击“地图”选项卡时才加载地图组件（及其依赖项）。这称为<a target="_blank" rel="noopener" href="https://www.patterns.dev/posts/import-on-interaction/">交互时导入</a>。</p>
<h1 id="CSS"><a href="#CSS" class="headerlink" title="CSS"></a>CSS</h1><p>如果运行示例代码，您将看到单击“位置”导航链接会加载地图组件。除了动态导入JS模块外，在组件的 <code>&lt;style&gt;</code> 块中导入依赖项也会延迟加载CSS：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">// In MapView<span class="selector-class">.vue</span></span><br><span class="line">&lt;style&gt;<span class="keyword">@import</span> <span class="string">&quot;../../node_modules/leaflet/dist/leaflet.css&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.map-wrapper</span> &#123;</span><br><span class="line">    aspect-ratio: <span class="number">16</span> / <span class="number">9</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure>

<h1 id="优化加载状态"><a href="#优化加载状态" class="headerlink" title="优化加载状态"></a>优化加载状态</h1><p>此时，我们的 API 请求并行运行，组件在不同的时间呈现。我们可能会注意到的一件事是页面看起来很卡顿，因为布局会有很多变化。</p>
<div id="dplayer1" class="dplayer hexo-tag-dplayer-mark" style="margin-bottom: 20px;"></div><script>(function(){var player = new DPlayer({"container":document.getElementById("dplayer1"),"theme":"#FADFA3","loop":true,"video":{"url":"https://gitee.com/wyatex/wyatex/raw/master/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/3.mp4"}});window.dplayers||(window.dplayers=[]);window.dplayers.push(player);})()</script>

<p>使用户感觉更流畅的一种快速方法是在小部件上设置一个大致对应于渲染组件的纵横比，这样用户就不会看到那么大的布局偏移。我们可以为此传递一个 prop 来解释不同的组件，并回退到默认值。</p>
<figure class="highlight js"><figcaption><span>WidgetLoader.vue</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;widget&quot;</span> <span class="attr">:style</span>=<span class="string">&quot;&#123; &#x27;aspect-ratio&#x27;: loading ? aspectRatio : &#x27;&#x27; &#125;&quot;</span> &gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">component</span> <span class="attr">:is</span>=<span class="string">&quot;AsyncComponent&quot;</span> <span class="attr">:data</span>=<span class="string">&quot;data&quot;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span> </span><br><span class="line">&lt;template&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">import</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    defineComponent,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    ref,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    onBeforeMount,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    onBeforeUnmount</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">&#125; <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">import</span> <span class="title class_">Loader</span> <span class="keyword">from</span> <span class="string">&quot;./Loader&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">import</span> <span class="title class_">Error</span> <span class="keyword">from</span> <span class="string">&quot;./Error&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">defineComponent</span>(&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="attr">components</span>: &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title class_">Loader</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="title class_">Error</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="attr">props</span>: &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="attr">aspectRatio</span>: &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                    <span class="attr">type</span>: <span class="title class_">String</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                    <span class="attr">default</span>: <span class="string">&quot;5 / 3&quot;</span>, <span class="comment">// define a default value</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="attr">url</span>: <span class="title class_">String</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="attr">importFunction</span>: <span class="title class_">Function</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            <span class="title function_">setup</span>(<span class="params">props</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="keyword">const</span> data = <span class="title function_">ref</span>(<span class="literal">null</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="keyword">const</span> loading = <span class="title function_">ref</span>(<span class="literal">true</span>);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                <span class="keyword">const</span> <span class="title function_">loadComponent</span> = (<span class="params"></span>) =&gt; &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="keyword">return</span> <span class="title function_">fetch</span>(url)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                            .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> response.<span class="title function_">json</span>())</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                            .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> (data.<span class="property">value</span> = response))</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                            .<span class="title function_">then</span>(importFunction</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                                .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">error</span>(e))</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                                .<span class="title function_">finally</span>(<span class="function">() =&gt;</span> (loading.<span class="property">value</span> = <span class="literal">false</span>)); <span class="comment">// Set the loading state to false</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                            &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="comment">/* ...Rest of the component code */</span></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        <span class="keyword">return</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                            data,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                            aspectRatio,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                            loading</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                        &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">                    &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">            &#125;); </span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

<h1 id="中止-API-请求"><a href="#中止-API-请求" class="headerlink" title="中止 API 请求"></a>中止 API 请求</h1><p>在包含大量 API 请求的页面上，如果用户在所有请求完成之前导航离开，会发生什么情况？我们可能不希望这些请求继续在后台运行，从而减慢用户体验。</p>
<p>我们可以使用AbortController接口，它使我们能够根据需要中止 API 请求。</p>
<p>在我们的 <code>setup</code> 函数中，我们创建一个新的控制器并将其信号传递到我们的获取请求参数中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">setup</span>(<span class="params">props</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> controller = <span class="keyword">new</span> <span class="title class_">AbortController</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> <span class="title function_">loadComponent</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">fetch</span>(url, &#123;</span><br><span class="line">                <span class="attr">signal</span>: controller.<span class="property">signal</span></span><br><span class="line">            &#125;)</span><br><span class="line">            .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> response.<span class="title function_">json</span>())</span><br><span class="line">            .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> (data.<span class="property">value</span> = response))</span><br><span class="line">            .<span class="title function_">then</span>(importFunction)</span><br><span class="line">            .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">error</span>(e))</span><br><span class="line">            .<span class="title function_">finally</span>(<span class="function">() =&gt;</span> (loading.<span class="property">value</span> = <span class="literal">false</span>));</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们在卸载组件之前中止请求，使用 Vue 的 <code>onBeforeUnmount</code> 函数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">onBeforeUnmount</span>(<span class="function">() =&gt;</span> controller.<span class="title function_">abort</span>());</span><br></pre></td></tr></table></figure>

<p>如果在请求完成之前运行项目并导航到另一个页面，则应在控制台中看到错误，指出请求已中止。</p>
<h1 id="使用-stale-while-revalidate-保持新鲜度"><a href="#使用-stale-while-revalidate-保持新鲜度" class="headerlink" title="使用 stale-while-revalidate 保持新鲜度"></a>使用 stale-while-revalidate 保持新鲜度</h1><p><em>Stale While Revalidate，说实话不知道怎么翻译了。。。</em></p>
<p>到目前为止，我们在优化应用程序方面做得很好。但是，当用户跳转到第二个路由，然后返回到前一个路由时，所有组件都会重新挂载并返回到其加载状态，我们必须重新等待请求响应。</p>
<p><code>stale-while-revalidate</code>是一种 HTTP 缓存失效策略，其中浏览器确定是提供来自缓存的响应（如果该内容仍然是最新的），还是“重新验证”并在响应过时时从网络提供。</p>
<p>除了将缓存控制标头应用于我们的 HTTP 响应（超出了本文的范围，但请阅读<a target="_blank" rel="noopener" href="https://web.dev/stale-while-revalidate/">Web.dev 本文</a>以获取更多详细信息），我们还可以使用SWRV库将类似的策略应用于我们的 Vue 组件状态。</p>
<p>首先，我们必须从 SWRV 库中导入组合式API：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> useSWRV <span class="keyword">from</span> <span class="string">&quot;swrv&quot;</span>;</span><br></pre></td></tr></table></figure>

<p>然后我们可以在我们的 <code>setup</code> 函数中使用它。我们将函数 <code>loadComponent</code> 重命名为 <code>fetchData</code>，因为它只处理数据获取。我们将不再在此函数中导入我们的组件，因为我们将单独处理。</p>
<p>我们将它作为第二个参数传递给 <code>useSWRV</code> 函数调用。只有当我们需要一个自定义函数来获取数据时，我们才需要这样做（也许我们需要更新一些其他状态）。当我们使用 Abort Controller 时，我们将执行此操作;否则，可以省略第二个参数，SWRV 将使用Fetch API：</p>
<figure class="highlight js"><figcaption><span>setup函数</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123; url, importFunction &#125; = props;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> controller = <span class="keyword">new</span> <span class="title class_">AbortController</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">fetchData</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title function_">fetch</span>(url, &#123; <span class="attr">signal</span>: controller.<span class="property">signal</span> &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> response.<span class="title function_">json</span>())</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> (data.<span class="property">value</span> = response))</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =&gt;</span> (error.<span class="property">value</span> = e));</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> &#123; data, isValidating, error &#125; = <span class="title function_">useSWRV</span>(url, fetchData);</span><br></pre></td></tr></table></figure>

<p>然后，我们将从异步组件定义中删除 <code>loadingComponent</code> 和 <code>errorComponent</code>，因为我们将使用 SWRV 来处理错误和加载状态。</p>
<figure class="highlight js"><figcaption><span>setup函数</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">AsyncComponent</span> = <span class="title function_">defineAsyncComponent</span>(&#123;</span><br><span class="line">  <span class="attr">loader</span>: importFunction,</span><br><span class="line">  <span class="attr">delay</span>: <span class="number">200</span>,</span><br><span class="line">  <span class="attr">timeout</span>: <span class="number">5000</span>,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>这意味着我们需要在模板中使用Loader和Error组件，并根据状态显示和隐藏它们。返回的isValidating告诉我们是否有请求或重新验证发生。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">Loader</span> <span class="attr">v-if</span>=<span class="string">&quot;isValidating &amp;&amp; !data&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">Loader</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">Error</span> <span class="attr">v-else-if</span>=<span class="string">&quot;error&quot;</span> <span class="attr">:errorMessage</span>=<span class="string">&quot;error.message&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">Error</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">component</span> <span class="attr">:is</span>=<span class="string">&quot;AsyncComponent&quot;</span> <span class="attr">:data</span>=<span class="string">&quot;data&quot;</span> <span class="attr">v-else</span>&gt;</span><span class="tag">&lt;/<span class="name">component</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&lt;/template&gt;</span><br><span class="line"></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">import</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  defineComponent,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  defineAsyncComponent,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">&#125; <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">import</span> useSWRV <span class="keyword">from</span> <span class="string">&quot;swrv&quot;</span>;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">defineComponent</span>(&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  <span class="attr">components</span>: &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="title class_">Error</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="title class_">Loader</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  <span class="attr">props</span>: &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="attr">url</span>: <span class="title class_">String</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="attr">importFunction</span>: <span class="title class_">Function</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  <span class="title function_">setup</span>(<span class="params">props</span>) &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="keyword">const</span> &#123; url, importFunction &#125; = props;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="keyword">const</span> controller = <span class="keyword">new</span> <span class="title class_">AbortController</span>();</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="keyword">const</span> <span class="title function_">fetchData</span> = (<span class="params"></span>) =&gt; &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="keyword">return</span> <span class="title function_">fetch</span>(url, &#123; <span class="attr">signal</span>: controller.<span class="property">signal</span> &#125;)</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> response.<span class="title function_">json</span>())</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> (data.<span class="property">value</span> = response))</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">        .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =&gt;</span> (error.<span class="property">value</span> = e));</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="keyword">const</span> &#123; data, isValidating, error &#125; = <span class="title function_">useSWRV</span>(url, fetchData);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="keyword">const</span> <span class="title class_">AsyncComponent</span> = <span class="title function_">defineAsyncComponent</span>(&#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="attr">loader</span>: importFunction,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="attr">delay</span>: <span class="number">200</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="attr">timeout</span>: <span class="number">5000</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    &#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="title function_">onBeforeUnmount</span>(<span class="function">() =&gt;</span> controller.<span class="title function_">abort</span>());</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    <span class="keyword">return</span> &#123;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      <span class="title class_">AsyncComponent</span>,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      isValidating,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      data,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">      error,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">    &#125;;</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">  &#125;,</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml">&#125;);</span></span></span><br><span class="line"><span class="language-javascript"><span class="language-xml"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

<p>我们可以将其重构为自己的组合式代码，使我们的代码更干净，使我们能够在任何地方使用它。</p>
<figure class="highlight js"><figcaption><span>composables/lazyFetch.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; onBeforeUnmount &#125; <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> useSWRV <span class="keyword">from</span> <span class="string">&quot;swrv&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">useLazyFetch</span>(<span class="params">url</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> controller = <span class="keyword">new</span> <span class="title class_">AbortController</span>();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">fetchData</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">fetch</span>(url, &#123; <span class="attr">signal</span>: controller.<span class="property">signal</span> &#125;)</span><br><span class="line">      .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> response.<span class="title function_">json</span>())</span><br><span class="line">      .<span class="title function_">then</span>(<span class="function">(<span class="params">response</span>) =&gt;</span> (data.<span class="property">value</span> = response))</span><br><span class="line">      .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =&gt;</span> (error.<span class="property">value</span> = e));</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> &#123; data, isValidating, error &#125; = <span class="title function_">useSWRV</span>(url, fetchData);</span><br><span class="line"></span><br><span class="line">  <span class="title function_">onBeforeUnmount</span>(<span class="function">() =&gt;</span> controller.<span class="title function_">abort</span>());</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    isValidating,</span><br><span class="line">    data,</span><br><span class="line">    error,</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><figcaption><span>WidgetLoader.vue</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; defineComponent, defineAsyncComponent, computed &#125; <span class="keyword">from</span> <span class="string">&quot;vue&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Loader</span> <span class="keyword">from</span> <span class="string">&quot;./Loader&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Error</span> <span class="keyword">from</span> <span class="string">&quot;./Error&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; useLazyFetch &#125; <span class="keyword">from</span> <span class="string">&quot;../composables/lazyFetch&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="title function_">defineComponent</span>(&#123;</span><br><span class="line">  <span class="attr">components</span>: &#123;</span><br><span class="line">    <span class="title class_">Error</span>,</span><br><span class="line">    <span class="title class_">Loader</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="attr">props</span>: &#123;</span><br><span class="line">    <span class="attr">aspectRatio</span>: &#123;</span><br><span class="line">      <span class="attr">type</span>: <span class="title class_">String</span>,</span><br><span class="line">      <span class="attr">default</span>: <span class="string">&quot;5 / 3&quot;</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">url</span>: <span class="title class_">String</span>,</span><br><span class="line">    <span class="attr">importFunction</span>: <span class="title class_">Function</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="title function_">setup</span>(<span class="params">props</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; aspectRatio, url, importFunction &#125; = props;</span><br><span class="line">    <span class="keyword">const</span> &#123; data, isValidating, error &#125; = <span class="title function_">useLazyFetch</span>(url);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> <span class="title class_">AsyncComponent</span> = <span class="title function_">defineAsyncComponent</span>(&#123;</span><br><span class="line">      <span class="attr">loader</span>: importFunction,</span><br><span class="line">      <span class="attr">delay</span>: <span class="number">200</span>,</span><br><span class="line">      <span class="attr">timeout</span>: <span class="number">5000</span>,</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      aspectRatio,</span><br><span class="line">      <span class="title class_">AsyncComponent</span>,</span><br><span class="line">      isValidating,</span><br><span class="line">      data,</span><br><span class="line">      error,</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h1 id="更新指示器"><a href="#更新指示器" class="headerlink" title="更新指示器"></a>更新指示器</h1><p>如果我们可以在请求重新验证时向用户显示指示器，以便他们知道应用程序正在查询新数据，这可能会很有用。在示例中，我在组件的一角添加了一个小的加载指示器，仅当已经有数据但组件正在检查更新时，才会显示该指示器。我还在组件上添加了一个简单的淡入过渡（使用 Vue 内置的 <code>Transition</code> 组件），因此在渲染组件时不会有如此突然的跳跃。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  <span class="language-xml"><span class="tag">&lt;<span class="name">div</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">    <span class="attr">class</span>=<span class="string">&quot;widget&quot;</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">    <span class="attr">:style</span>=<span class="string">&quot;&#123; &#x27;aspect-ratio&#x27;: isValidating &amp;&amp; !data ? aspectRatio : &#x27;&#x27; &#125;&quot;</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">  &gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">Loader</span> <span class="attr">v-if</span>=<span class="string">&quot;isValidating &amp;&amp; !data&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">Loader</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">Error</span> <span class="attr">v-else-if</span>=<span class="string">&quot;error&quot;</span> <span class="attr">:errorMessage</span>=<span class="string">&quot;error.message&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">Error</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">Transition</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">component</span> <span class="attr">:is</span>=<span class="string">&quot;AsyncComponent&quot;</span> <span class="attr">:data</span>=<span class="string">&quot;data&quot;</span> <span class="attr">v-else</span>&gt;</span><span class="tag">&lt;/<span class="name">component</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">Transition</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"></span></span><br><span class="line"><span class="language-xml">    <span class="comment">&lt;!--Indicator if data is updating--&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">Loader</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">      <span class="attr">v-if</span>=<span class="string">&quot;isValidating &amp;&amp; data&quot;</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">      <span class="attr">text</span>=<span class="string">&quot;&quot;</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">    &gt;</span><span class="tag">&lt;/<span class="name">Loader</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&lt;/template&gt;</span><br></pre></td></tr></table></figure>

<h1 id="结论"><a href="#结论" class="headerlink" title="结论"></a>结论</h1><p>在构建我们的 Web 应用程序时优先考虑性能可以改善用户体验，并有助于确保尽可能多的人可以使用它们。我们已经在 Ada Mode 中成功使用了上述技术来加快我们的应用程序。我希望本文提供了一些关于如何使您的应用程序尽可能高效的指示 - 无论您选择全部还是部分实现它们。</p>
<p>SPA 可以做的很好，但它们也可能是性能瓶颈。所以，让我们尝试更好地编写SPA应用吧。</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/Vue/%E4%BC%98%E5%8C%96%E4%BD%A0%E7%9A%84Vue%E5%BA%94%E7%94%A8/" title="优化你的Vue应用">https://wyatex.online/Vue/优化你的Vue应用/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/JavaScript-%E5%89%8D%E7%AB%AF-%E7%BF%BB%E8%AF%91-Vue/" rel="tag"># + JavaScript + 前端 + 翻译 + Vue</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/Flutter/flutter%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91-1/" rel="prev" title="flutter的一些坑（1）">
                  <i class="fa fa-angle-left"></i> flutter的一些坑（1）
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/%E7%AC%94%E8%AE%B0/ubuntu%E5%AE%89%E8%A3%85Python/" rel="next" title="ubuntu安装Python">
                  ubuntu安装Python <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
